package com.atzly.community.controller.interceptor;

import com.atzly.community.entity.User;
import com.atzly.community.service.AccessCountService;
import com.atzly.community.utils.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *  统计访问数据拦截器
 * @author zlysimida
 * @date 2021/12/25 - 20:28
 */
@Component
public class AccessRequireInterceptor implements HandlerInterceptor {

    @Autowired
    private AccessCountService accessCountService;

    @Autowired
    private HostHolder hostHolder;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 统计uv 独立访客
        String ip = request.getRemoteHost();
        accessCountService.recordUV(ip);
        // 统计dau
        User user = hostHolder.getUserFromThread();
        if(user != null) {
            accessCountService.recordDAU(user.getId());
        }
        return true;
    }
}
